import 'dart:async';

import 'package:enterprise_v6_app/app/components/dialog/custom_callback_general_dialog.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/education/couser_center/get_detail_by_id_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/get_new_dict_all_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/education/quiz/model.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';
import 'package:get/get.dart';

///调查问卷
class QuestionnaireDetailController extends GetxController {
  /// 构造器
  QuestionnaireDetailController(this.leftSeconds) {
    timer = Timer.periodic(const Duration(seconds: 1), (_) {
      if (timer == null) return;
      if (leftSeconds <= 0) {
        _disposeTimer();
        Get.back();
        //时间到啦 跳页面
        Get.toNamed(AppRoutes.findingsPage);
        return;
      }
      leftSeconds--;
      update();
    });
  }

  /// 请求参数
  Map<String, dynamic> queryParameters = {};

  //总秒
  int leftSeconds;
  Timer? timer;

  void _disposeTimer() {
    timer?.cancel();
    timer = null;
  }

  /// 题目界面字体显示大小
  final textSize = QuizTextSize.small.obs;

  /// 我的建议
  String meContent = '';

  ///点击效果
  bool checkboxSelected = false;

  ///需求id
  String id = '';

  ///答题过后 提交集合
  List questionAnswerDTOList = [];

  /// 剩余时间，转换
  QuizLeftTime get leftTime {
    final left = leftSeconds;
    final hours = left ~/ 3600;
    final minutes = (left % 3600) ~/ 60;
    final seconds = left % 60;
    return QuizLeftTime(hours: hours, minutes: minutes, seconds: seconds);
  }

  @override
  void onInit() {
    super.onInit();
    if (Get.arguments['id'] != null) {
      id = Get.arguments['id'] as String;
    }
    if (Get.arguments['questionAnswerDTOList'] != null) {
      questionAnswerDTOList = Get.arguments['questionAnswerDTOList'] as List;
    }

    //获取学习主题
    // getJypxztQ1uSZQaD();
    getDetailById();
  }

  List<GetDetailByIdSurveyTypes> jypxztQ1uSZQaD = [];

  ///调查问卷详情
  void getDetailById() async {
    queryParameters['id'] = Get.arguments['id']; //id
    final res = await HttpUtil()
        .generateGetRequest<GetDetailByIdEntity>(
          Interface.getDetailById,
          queryParameters: queryParameters,
        )
        .execute();
    res.onSuccess((result) {
      if (result.data != null) {
        final GetDetailByIdEntity dataSelect = result.data!;
        jypxztQ1uSZQaD = dataSelect.surveyTypes ?? [];
      }
    });
    update();
  }

  ///flattenTreeList 函数递归地将树形结构的列表转换为一个平铺的列表。对于每个节点，它将节点本身添加到结果列表中，
  ///然后递归地处理节点的子节点。最后，flatList 包含了原始树形结构列表中所有节点的一个平铺版本
  List<GetNewDictAllEntity> flattenTreeList(List<GetNewDictAllEntity> nodeList) {
    final List<GetNewDictAllEntity> flatList = [];

    for (var node in nodeList) {
      flatList.add(node);
      if (node.dictionaryDetails!.isNotEmpty) {
        flatList.addAll(flattenTreeList(node.dictionaryDetails!));
      }
    }
    return flatList;
  }

  ///跳转页面
  void onClickToPage() async {
    //主题id
    final List<String> questionValidity = [];
    //主体Name
    final List<String> questionValidityName = [];
    //判断
    for (var value in jypxztQ1uSZQaD) {
      //获取选中的主题id
      if (value.checkboxSelected) {
        questionValidity.add(value.id ?? '');
        questionValidityName.add(value.surveyTypeDicName ?? '');
      }
    }
    if (questionValidity.isEmpty) {
      AppToast.showWarning('请选择学习专题');
      return;
    }
    await Get.dialog<bool>(
          CustomGeneralCallbackDialog(
            content: '你选择了${questionValidity.length}个专题，确认提交吗？',
            onPressed: () {
              //调接口 提交
              educationSurveyAnswer(id, questionAnswerDTOList, meContent, questionValidity, questionValidityName);
            },
          ),
        ) ??
        false;
  }

  ///	需求调研ID  '问题答案'	我的建议  	主题ID集合
  void educationSurveyAnswer(
      String id, List questionAnswerDTOList, String recommendation, List<String> surveyTypeIds, List<String> questionValidityName) async {
    final res = await HttpUtil().generatePostRequest(
      Interface.answer,
      data: {'id': id, 'questionAnswerDTOList': questionAnswerDTOList, 'recommendation': recommendation, 'surveyTypeIds': surveyTypeIds},
    ).execute();
    res.onSuccess((result) {
      Get.back();
      Get.back();
      AppToast.showSuccess(result.message);
      _disposeTimer();
      //主题  建议
      Get.toNamed(AppRoutes.findingsPage, arguments: {
        'recommendation': recommendation,
        'questionValidityName': questionValidityName,
      });
    });
  }
}
